package com.zy.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
@Slf4j
public class LoginController {
    @GetMapping("/login")
    public String login(){
        return "login";
    }
    @PostMapping("/login")
    public String login(String userCode,String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userCode,password);
        subject.login(token);
        System.out.println("登陆成功----------------------------------");
        log.info("登陆成功"+subject.isAuthenticated());
        return "redirect:/index";
    }
    @ExceptionHandler({RuntimeException.class})
    public void handlerException(RuntimeException e, Model model){
        String msg="";
        if(e instanceof UnknownAccountException){
            msg="用户名或者密码错误";
        }else if(e instanceof IncorrectCredentialsException){
            msg="用户名或者密码错误";
        }else{
            msg="其他错误";
        }
        model.addAttribute("loginErr",msg);
    }
}
